<?

if (eregi(basename(__FILE__), $_SERVER['PHP_SELF'])) {
    print "<h1>Incorrect access</h1>You cannot access this file directly.";
    exit();
}

class ajax_upload {

    function playme() {
        $code = AZLib::getParam('code');
        switch ($code) {
            case 'gallery_upload':
                $this->gallery_upload();
                break;
            case 'gallery_update':
                $this->gallery_update();
                break;
            case 'item_image':
                $this->item_image_upload();
                break;
            case 'get_gallery':
                $this->get_gallery();
                break;
            case 'get_gallery_entry':
                $this->get_gallery_entry();
                break;
            case 'gallery_delete'://Xoá ảnh
                $this->gallery_delete();
                break;
            case 'gallery_bulk_delete'://Xoá nhiều ảnh
                $this->gallery_bulk_delete();
                break;
            case 'crop_image':
                $this->item_image_crop();
                break;
            default:
                $this->home();
                break;
        }
    }

    function home() {
        global $display;
        die("Nothing to do...");
    }

    function gallery_upload() {//Upload ảnh cho thư viện
        if (User::have_permit(ADMIN_IMAGE) && (int) Url::get('user_id', 0) && (int) Url::get('user_id', 0) != User::id()) {
            $user_id = (int) Url::get('user_id', 0);
            $user_name = '';
            $user = User::getUser($user_id);
            if ($user)
                $user_name = $user['user_name'];
        }
        else {
            $user_id = User::id();
            $user_name = User::user_name();
        }

        $id = (int) $_GET['id'];
        $json['error'] = 'not_uploaded';
        $json['url_error'] = '';
        $json['des'] = '';

        $json['id'] = 0;
        $json['time'] = 0;
        $json['image_path'] = IMAGE_PATH;
        $json['image_url'] = '';

        if (User::is_login()) {
            if (User::is_az_team() || User::level() > 0) {
                if ($id) {
                    $des = substr(AZLib::trimSpace(AZLib::cleanHtml($_POST['des'][$id])), 0, 50);
                    $upload_path = AZLib::folderUpload($user_id);

                    if (AZLib::ftp_check_dir($upload_path, true, IMAGE_SERVER_NO)) {//Check dir for upload
                        if (isset($_FILES['img_upload']) && !$_FILES['img_upload']['error'][$id] && $_FILES['img_upload']['name'][$id]) {
                            if (getimagesize($_FILES['img_upload']['tmp_name'][$id]) && $_FILES['img_upload']['size'][$id] <= Item::MAX_UPLOAD_SIZE) {
                                $file_name = strtolower($_FILES['img_upload']['name'][$id]);
                                $sourceName = $_FILES['img_upload']['tmp_name'][$id];
                                $file_ext = AZLib::getExtension($file_name);

                                if (in_array($file_ext, array('.jpg', '.jpeg', '.gif', '.png'))) {
                                    $img_url = $upload_path . date("YmdHis", TIME_NOW) . '_' . substr(AZLib::make_safe_name(basename(strtolower($file_name), $file_ext)), 0, 36) . $file_ext;

                                    if (AZLib::ftp_image_put_file($img_url, $sourceName, IMAGE_SERVER_NO)) {
                                        $image_id = DB::insert('item_image', array(
                                                    'des' => $des,
                                                    'item_id' => 0,
                                                    'title' => '',
                                                    'position' => 0,
                                                    'img_server' => IMAGE_SERVER_NO,
                                                    'img_url' => $img_url,
                                                    'root_id' => 0,
                                                    'time' => TIME_NOW,
                                                    'user_id' => $user_id,
                                                    'user_name' => $user_name
                                                ));
                                        if ($image_id) {
                                            $json['id'] = $image_id;
                                            $json['img_server'] = IMAGE_SERVER_NO;

                                            $json['time'] = date('H:i', TIME_NOW);
                                            $json['image_url'] = $img_url;

                                            $json['error'] = 'success';
                                        }
                                    }
                                } else {
                                    $json['error'] = 'ext_invalid'; //Sai định dạng file
                                }
                            } else {
                                $json['error'] = 'over_max_size'; //Sai định dạng file hoặc upload dung lượng quá lớn
                            }
                        } elseif ($_POST['url'][$id]) {
                            $url = $_POST['url'][$id];
                            $tem_cache_dir = DIR_CACHE . 'user_images/';
                            AZLib::CheckDir($tem_cache_dir);

                            $tem_cache_file = User::user_name() . md5($url) . '.gif';
                            $image_content = disguise_curl($url);

                            if ($image_content) {
                                if (@file_put_contents($tem_cache_dir . $tem_cache_file, $image_content)) {
                                    if (getimagesize($tem_cache_dir . $tem_cache_file) && filesize($tem_cache_dir . $tem_cache_file) <= Item::MAX_UPLOAD_SIZE) {
                                        $sourceName = $tem_cache_dir . $tem_cache_file;

                                        $img_url = $upload_path . TIME_NOW . '_' . $tem_cache_file;
                                        if (AZLib::ftp_image_put_file($img_url, $sourceName, IMAGE_SERVER_NO)) {
                                            $image_id = DB::insert('item_image', array(
                                                        'des' => $des,
                                                        'item_id' => 0,
                                                        'title' => '',
                                                        'position' => 0,
                                                        'img_server' => IMAGE_SERVER_NO,
                                                        'img_url' => $img_url,
                                                        'root_id' => 0,
                                                        'time' => TIME_NOW,
                                                        'user_id' => $user_id,
                                                        'user_name' => $user_name
                                                    ));

                                            if ($image_id) {
                                                $json['id'] = $image_id;
                                                $json['img_server'] = IMAGE_SERVER_NO;
                                                $json['time'] = date('H:i', TIME_NOW);
                                                $json['image_url'] = $img_url;

                                                $json['url_error'] = 'success';
                                            }
                                            else
                                                $json['url_error'] = 'over_max_size';
                                        }
                                        else
                                            $json['url_error'] = 'not_uploaded';
                                    }
                                    else
                                        $json['url_error'] = 'over_max_size';

                                    @unlink($tem_cache_dir . $tem_cache_file);
                                }
                                else
                                    $json['url_error'] = 'not_cache_file';
                            }
                            else
                                $json['url_error'] = 'not_get_img';
                        }
                        elseif ($_FILES['img_upload']['error'][$id] == 1) {
                            $json['error'] = 'over_max_size';
                        }

                        $json['des'] = $des;
                    }
                }
            }
        } else {
            $json['error'] = 'not_login';
        }

        echo json_encode($json);
        exit();
    }

    function gallery_update() {//Cập nhật ảnh cho thư viện
        if (User::have_permit(ADMIN_IMAGE) && (int) Url::get('user_id', 0) && (int) Url::get('user_id', 0) != User::id()) {
            $user_id = (int) Url::get('user_id', 0);
        } else {
            $user_id = User::id();
        }

        $image_id = (int) $_GET['image_id'];
        $json['error'] = 'not_updated'; //not_uploaded
        $json['url_error'] = '';
        $json['img_url'] = '';

        if (User::is_login()) {
            if (User::is_az_team() || User::level() > 0) {
                if ($image_id) {
                    $des = substr(AZLib::trimSpace(AZLib::cleanHtml($_POST['des_update'])), 0, 50);
                    $image = DB::select('item_image', 'id=' . $image_id . ' AND root_id=0 AND user_id=' . $user_id);

                    if ($image) {
                        $upload_path = AZLib::folderUpload($user_id);

                        if (AZLib::ftp_check_dir($upload_path, true, IMAGE_SERVER_NO)) {//Check dir for upload
                            if (isset($_FILES['img_upload_update']) && !$_FILES['img_upload_update']['error'] && $_FILES['img_upload_update']['name']) {
                                if (getimagesize($_FILES['img_upload_update']['tmp_name']) && $_FILES['img_upload_update']['size'] <= Item::MAX_UPLOAD_SIZE) {
                                    $file_name = $_FILES['img_upload_update']['name'];
                                    $sourceName = $_FILES['img_upload_update']['tmp_name'];
                                    $file_ext = AZLib::getExtension($file_name);

                                    if (in_array($file_ext, array('.jpg', '.jpeg', '.gif', '.png'))) {
                                        $img_url = $upload_path . date("YmdHis", TIME_NOW) . '_' . substr(AZLib::make_safe_name(basename(strtolower($file_name), $file_ext)), 0, 36) . $file_ext;

                                        if (AZLib::ftp_image_put_file($img_url, $sourceName, IMAGE_SERVER_NO)) {
                                            if (DB::update('item_image', array(
                                                        'des' => $des,
                                                        'img_server' => IMAGE_SERVER_NO,
                                                        'img_url' => $img_url
                                                            ), 'id=' . $image_id . ' OR root_id=' . $image_id)) {
                                                if ($image['img_url']) {
                                                    AZLib::ftp_image_delete_file($image['img_url'], $image['img_server']);

                                                    if (MEMCACHE_ON) {

                                                        $sql = "SELECT * FROM item	WHERE img_url='{$image['img_url']}' AND status IN(1,2)  AND user_id=" . $user_id;
                                                        $re = DB::query($sql);

                                                        while ($item_memcache = mysql_fetch_assoc($re)) {
                                                            $item_memcache['img_server'] = IMAGE_SERVER_NO;
                                                            $item_memcache['img_url'] = $img_url;
                                                            AZMemcache::do_put("item:" . $item_memcache['id'], $item_memcache);
                                                        }
                                                    }

                                                    DB::query("UPDATE item SET img_server = " . (int) IMAGE_SERVER_NO . ", img_url='{$img_url}' WHERE img_url='{$image['img_url']}' AND status IN(1,2)  AND user_id=" . $user_id);
                                                }
                                                $json['img_server'] = IMAGE_SERVER_NO;
                                                $json['img_url'] = $img_url;
                                                $json['error'] = 'success';
                                            } else {
                                                $json['error'] = 'not_updated';
                                            }
                                        }
                                    } else {
                                        $json['error'] = 'ext_invalid'; //Sai định dạng file
                                    }
                                } else {
                                    $json['error'] = 'over_max_size'; //Sai định dạng file hoặc upload dung lượng quá lớn
                                }
                            } elseif ($_POST['url_update']) {
                                $url = $_POST['url_update'];

                                $tem_cache_dir = DIR_CACHE . 'user_images/';
                                AZLib::CheckDir($tem_cache_dir);

                                $tem_cache_file = User::user_name() . md5($url) . '.gif';
                                $image_content = disguise_curl($url);

                                if ($image_content) {
                                    if (@file_put_contents($tem_cache_dir . $tem_cache_file, $image_content)) {
                                        if (getimagesize($tem_cache_dir . $tem_cache_file) && filesize($tem_cache_dir . $tem_cache_file) <= Item::MAX_UPLOAD_SIZE) {
                                            $sourceName = $tem_cache_dir . $tem_cache_file;
                                            $img_url = $upload_path . TIME_NOW . '_' . $tem_cache_file;

                                            if (AZLib::ftp_image_put_file($img_url, $sourceName, IMAGE_SERVER_NO)) {
                                                if (DB::update('item_image', array(
                                                            'des' => $des,
                                                            'img_server' => IMAGE_SERVER_NO,
                                                            'img_url' => $img_url)
                                                                , 'id=' . $image_id . ' OR root_id=' . $image_id)) {
                                                    if ($image['img_url']) {
                                                        AZLib::ftp_image_delete_file($image['img_url'], $image['imng_server']);
                                                        if (MEMCACHE_ON) {
                                                            $sql = "SELECT * FROM item	WHERE img_url='{$image['img_url']}' AND status IN(1,2)  AND user_id=" . $user_id;
                                                            $re = DB::query($sql);

                                                            while ($item_memcache = mysql_fetch_assoc($re)) {
                                                                $item_memcache['img_server'] = IMAGE_SERVER_NO;
                                                                $item_memcache['img_url'] = $img_url;
                                                                AZMemcache::do_put("item:" . $item_memcache['id'], $item_memcache);
                                                            }
                                                        }

                                                        DB::query("UPDATE item SET img_url='{$img_url}' WHERE img_url='{$image['img_url']}' AND status IN(1,2) AND user_id=" . $user_id);
                                                    }
                                                    $json['url_error'] = 'success';
                                                    $json['img_server'] = IMAGE_SERVER_NO;
                                                    $json['img_url'] = $img_url;
                                                } else {
                                                    $json['url_error'] = 'not_updated';
                                                }
                                            }
                                            else
                                                $json['url_error'] = 'not_uploaded';
                                        }
                                        else
                                            $json['url_error'] = 'over_max_size';

                                        @unlink($tem_cache_dir . $tem_cache_file);
                                    }
                                    else
                                        $json['url_error'] = 'not_cache_file';
                                }
                                else
                                    $json['url_error'] = 'not_get_img';
                            }
                            else {
                                if ($des != $image['des']) {
                                    if (DB::update('item_image', array('des' => $des), 'id=' . $image_id)) {
                                        $json['error'] = 'success';
                                    } else {
                                        $json['error'] = 'not_updated';
                                    }
                                } else {
                                    $json['error'] = 'success';
                                }
                            }
                        }
                        $json['des'] = $des;

                        //get Item_id
                        $sql = "SELECT item_id FROM item_image WHERE (id = $image_id OR root_id = $image_id) " . (User::have_permit(ADMIN_IMAGE) ? '' : " AND user_id=" . User::id());
                        $re = DB::query($sql);

                        if ($re) {
                            $item = mysql_fetch_assoc($re);
                            if ($item["item_id"]) {
                                require_once ROOT_PATH . 'core/Item.php';
                                Item::get_item_images($item["item_id"], 1);
                            }
                        }
                    } else {
                        $json['error'] = 'not_exit';
                    }

                    //get Item_id
                    $sql = "SELECT item_id FROM item_image WHERE id = $image_id";
                    $re = DB::query($sql);
                    if ($re) {
                        $item = mysql_fetch_assoc($re);
                        require_once ROOT_PATH . 'core/Item.php';
                        Item::get_item_images($item["item_id"], 1);
                    }
                }
            }
        } else {
            $json['error'] = 'not_login';
        }

        echo json_encode($json);
        exit();
    }

    function item_image_crop() {
        if ((User::have_permit(ADMIN_ITEM) || User::is_mod()) && (int) Url::get('user_id', 0) && (int) Url::get('user_id', 0) != User::id()) {
            $user_id = (int) Url::get('user_id', 0);
            $user_name = '';
            $user = User::getUser($user_id);
            if ($user)
                $user_name = $user['user_name'];
        }
        else {
            $user_id = User::id();
            $user_name = User::user_name();
        }
        $arrRet['result'] = false;
        $arrRet['id'] = 0;
        $arrRet['img_url'] = '';
        $arrRet['img_server'] = IMAGE_SERVER_NO;
        $arrRet['message'] = 'Unknown Error';

        if (User::is_login()) {
            if (User::is_az_team() || User::level() > 0) {
                $upload_path = DIR_CACHE . 'crop_images/';
                AZLib::CheckDir($upload_path);

                // Thông số crop ảnh
                $cropX1 = $_REQUEST["cropX1"];
                $cropY1 = $_REQUEST["cropY1"];
                $cropWidth = $_REQUEST["cropWidth"];
                $cropHeight = $_REQUEST["cropHeight"];
                $displayWidth = $_REQUEST["displayWidth"];
                $displayHeight = $_REQUEST["displayHeight"];
                $imgServer = $_REQUEST["imgServerPath"];

                //$imgServerAddress = "192.168.28.200/images.enbac.com/";
                $imageFileName = $_REQUEST['imgPath'];
                $desImageName = AZLib::genUniqueFileName($imageFileName);
                $newImage = $upload_path . $desImageName;

                $imageName = "http://$imgServer" . $imageFileName;

                list($imagewidth, $imageheight, $imageType) = getimagesize($imageName);

                if ($imagewidth) {
                    //if((int)ini_get("memory_limit")<64){@ini_set("memory_limit","64M");}

                    $scaleW = $imagewidth / $displayWidth;
                    $scaleH = $imageheight / $displayHeight;
                    $w = (int) ($cropWidth * $scaleW);
                    $h = (int) ($cropHeight * $scaleH);
                    $x1 = (int) ($cropX1 * $scaleW);
                    $y1 = (int) ($cropY1 * $scaleH);

                    $imageType = image_type_to_mime_type($imageType);
                    $cropName = $upload_path . $desImageName;

                    if ($imageType) {
                        switch ($imageType) {
                            case "image/gif":
                                $source = imagecreatefromgif($imageName);
                                break;
                            case "image/pjpeg":
                            case "image/jpeg":
                            case "image/jpg":
                                $source = imagecreatefromjpeg($imageName);
                                break;
                            case "image/png":
                            case "image/x-png":
                                $source = imagecreatefrompng($imageName);
                                break;
                        }

                        if ($source) {
                            $newImg = imagecreatetruecolor($w, $h);
                            if ($newImg) {
                                if (imagecopyresampled($newImg, $source, 0, 0, $x1, $y1, $w, $h, $w, $h)) {


                                    switch ($imageType) {
                                        case "image/gif":
                                            $createdImage = imagegif($newImg, $cropName);
                                            break;
                                        case "image/pjpeg":
                                        case "image/jpeg":
                                        case "image/jpg":
                                            $createdImage = imagejpeg($newImg, $cropName, 99);
                                            break;
                                        case "image/png":
                                        case "image/x-png":
                                            $createdImage = imagepng($newImg, $cropName);
                                            break;
                                    }
                                    if ($createdImage) {
                                        $img_url = '';
                                        $upload_path = AZLib::folderUpload($user_id);

                                        if (AZLib::ftp_check_dir($upload_path, true, IMAGE_SERVER_NO)) {//Check dir for upload
                                            $file_ext = AZLib::getExtension($imageFileName);

                                            $img_url = $upload_path . date("YmdHis", TIME_NOW) . '_' . substr(AZLib::make_safe_name(basename(strtolower($imageFileName), $file_ext)), 0, 36) . $file_ext;

                                            AZLib::ftp_image_put_file($img_url, $cropName, IMAGE_SERVER_NO);
                                            $return = 'true';
                                        } else {
                                            $return = 'false,Destination folder not exist';
                                        }
                                    } else {
                                        $return = 'false,Refine image failed';
                                    }
                                } else {
                                    $return = 'false,Crop image failed';
                                }
                            } else {
                                $return = 'false,Verify image color failed';
                            }
                        } else {
                            $return = 'false,Get image source failed';
                        }
                    } else {
                        $return = 'false,Image type is not supported';
                    }
                } else {
                    $return = 'false,The source file is not an image';
                }

                if ($return == 'true') {
                    // Tạo ảnh mới trong gallery của user
                    $image_id = DB::insert('item_image', array(
                                'des' => '',
                                'item_id' => 0,
                                'title' => '',
                                'position' => 0,
                                'img_server' => IMAGE_SERVER_NO,
                                'img_url' => $img_url,
                                'root_id' => 0,
                                'time' => TIME_NOW,
                                'user_id' => $user_id,
                                'user_name' => $user_name
                            ));
                    $arrRet['result'] = true;
                    $arrRet['id'] = $image_id;
                    $arrRet['img_url'] = $img_url;
                    $arrRet['img_server'] = IMAGE_SERVER_NO;
                    $arrRet['message'] = 'Success';
                } else {
                    $arrCURLRet = split(',', $return);
                    if (count($arrCURLRet) > 1) {
                        $arrRet['message'] = $arrCURLRet[1];
                    }
                }
            } else {
                $arrRet['message'] = 'The image server could not be found';
            }
        } else {
            $arrRet['message'] = 'You don\'t have permission to edit this image';
        }

        echo json_encode($arrRet);
        exit();
    }

    function item_image_upload() {//
        if ((User::have_permit(ADMIN_ITEM) || User::is_mod()) && (int) Url::get('user_id', 0) && (int) Url::get('user_id', 0) != User::id()) {
            $user_id = (int) Url::get('user_id', 0);
            $user_name = '';
            $user = User::getUser($user_id);
            if ($user)
                $user_name = $user['user_name'];
        }
        else {
            $user_id = User::id();
            $user_name = User::user_name();
        }

        $json['error'] = 'not_uploaded';
        $json['id'] = 0;
        $json['image_url'] = '';

        if (User::is_login()) {
            if (User::is_az_team() || User::level() > 0) {
                $upload_path = AZLib::folderUpload($user_id);

                if (AZLib::ftp_check_dir($upload_path, true, IMAGE_SERVER_NO)) {//Check dir for upload
                    if (isset($_FILES['img_upload']) && !$_FILES['img_upload']['error'] && $_FILES['img_upload']['name']) {
                        list($imagewidth, $imageheight, $imageType) = getimagesize($_FILES['img_upload']['tmp_name']);
                        if ($imagewidth && $_FILES['img_upload']['size'] <= Item::MAX_UPLOAD_SIZE) {
                            /* if(($imagewidth > 479)||($imageheight > 359))
                              {
                              if($imagewidth > 479)//&& ($imagewidth < 1281) && ($imageheight < 1025))
                              {
                              if($imageheight > 359)
                              { */
                            $file_name = $_FILES['img_upload']['name'];
                            $sourceName = $_FILES['img_upload']['tmp_name'];
                            $file_ext = AZLib::getExtension($file_name);

                            if (in_array($file_ext, array('.jpg', '.jpeg', '.gif', '.png'))) {
                                $img_url = $upload_path . date("YmdHis", TIME_NOW) . '_' . substr(AZLib::make_safe_name(basename(strtolower($file_name), $file_ext)), 0, 36) . $file_ext;
                                /* $json['error'] = AZLib::ftp_image_put_file($img_url, $sourceName, IMAGE_SERVER_NO);
                                  echo json_encode($json);
                                  exit; */
                                if (AZLib::ftp_image_put_file($img_url, $sourceName, IMAGE_SERVER_NO)) {
                                    $image_id = DB::insert('item_image', array(
                                                'des' => '',
                                                'item_id' => 0,
                                                'title' => '',
                                                'position' => 0,
                                                'img_server' => IMAGE_SERVER_NO,
                                                'img_url' => $img_url,
                                                'root_id' => 0,
                                                'time' => TIME_NOW,
                                                'user_id' => $user_id,
                                                'user_name' => $user_name
                                            ));
                                    if ($image_id) {
                                        $json['id'] = $image_id;
                                        $json['img_server'] = IMAGE_SERVER_NO;
                                        $json['image_url'] = $img_url;

                                        $json['error'] = 'success';
                                    }
                                }
                            } else {
                                $json['error'] = 'ext_invalid'; //Sai định dạng file
                            }
                            /* }
                              else
                              {
                              $json['error'] = 'height_not_allow';
                              }
                              }
                              else
                              {
                              $json['error'] = 'width_not_allow';
                              }
                              }
                              else
                              {
                              $json['error'] = 'width_n_height_not_allow';
                              } */
                        } else {
                            $json['error'] = 'over_max_size'; //Sai định dạng file hoặc upload dung lượng quá lớn
                        }
                    } elseif ($_POST['url'] && $_POST['url'] != 'Hoặc Url') {
                        $url = $_POST['url'];

                        $tem_cache_dir = DIR_CACHE . 'user_images/';
                        AZLib::CheckDir($tem_cache_dir);

                        $tem_cache_file = User::user_name() . md5($url) . '.gif';
                        $image_content = disguise_curl($url);

                        if ($image_content) {
                            if (@file_put_contents($tem_cache_dir . $tem_cache_file, $image_content)) {
                                if (getimagesize($tem_cache_dir . $tem_cache_file) && filesize($tem_cache_dir . $tem_cache_file) <= Item::MAX_UPLOAD_SIZE) {
                                    $sourceName = $tem_cache_dir . $tem_cache_file;

                                    $img_url = $upload_path . TIME_NOW . '_' . $tem_cache_file;
                                    //$json['error'] = AZLib::ftp_image_put_file($img_url, $sourceName, IMAGE_SERVER_NO);
                                    //echo json_encode($json);
                                    //exit;
                                    if (AZLib::ftp_image_put_file($img_url, $sourceName, IMAGE_SERVER_NO)) {
                                        $image_id = DB::insert('item_image', array(
                                                    'des' => '',
                                                    'item_id' => 0,
                                                    'title' => '',
                                                    'position' => 0,
                                                    'img_server' => IMAGE_SERVER_NO,
                                                    'img_url' => $img_url,
                                                    'root_id' => 0,
                                                    'time' => TIME_NOW,
                                                    'user_id' => $user_id,
                                                    'user_name' => $user_name
                                                ));

                                        if ($image_id) {
                                            $json['id'] = $image_id;
                                            $json['img_server'] = IMAGE_SERVER_NO;
                                            $json['image_url'] = $img_url;

                                            $json['url_error'] = 'success';
                                        }
                                        else
                                            $json['url_error'] = 'over_max_size';
                                    }
                                    else
                                        $json['url_error'] = 'not_uploaded';
                                }
                                else
                                    $json['url_error'] = 'over_max_size';

                                @unlink($tem_cache_dir . $tem_cache_file);
                            }
                            else
                                $json['url_error'] = 'not_cache_file';
                        }
                        else
                            $json['url_error'] = 'not_get_img';
                    }
                    elseif ($_FILES['img_upload']['error'] == 1) {
                        $json['error'] = 'over_max_size';
                    }
                }
            }
        } else {
            $json['error'] = 'not_login';
        }

        echo json_encode($json);
        exit();
    }

    function get_gallery() {
        global $display;

        if (User::is_login()) {
            $user_id = (int) Url::get('user_id', 0);

            if ((User::have_permit(ADMIN_ITEM) || User::is_mod()) && $user_id && $user_id != User::id()) {
                $display->add('user_id', $user_id);
            }
            else
                $user_id=User::id();

            $search_value = ' user_id=' . $user_id . ' AND root_id=0 ';

            //search theo ngay thang nam
            //$year=(int)Url::get('year',date('Y'));
            $year = (int) Url::get('year', -1);
            //$mon= (int)Url::get('month',(int)date('m'));
            $mon = (int) Url::get('month', -1);
            $day = (int) Url::get('day', -1);

            if ($year == 0

                )$year = -1;
            if ($mon == 0

                )$mon = -1;
            if ($day == 0

                )$day = -1;

            $created_time_from = 0;
            $created_time_to = 0;

            if ($year != -1) {
                if ($mon != -1) {
                    if ($day != -1) {
                        $created_time_from = mktime(0, 0, 0, $mon, $day, $year);
                        $created_time_to = mktime(23, 59, 59, $mon, $day, $year);
                    } else {
                        $max_day = 31;
                        if (in_array($mon, array(4, 6, 9, 11))
                        
                            )$max_day = 30;
                        elseif ($mon == 2)
                            ($year % 4) ? $max_day = 28 : $max_day = 29;

                        $created_time_from = mktime(0, 0, 0, $mon, 1, $year);
                        $created_time_to = mktime(23, 59, 59, $mon, $max_day, $year);
                    }
                }
                else {
                    $created_time_from = mktime(0, 0, 0, 1, 1, $year);
                    $created_time_to = mktime(23, 59, 59, 12, 31, $year);
                }
            }

            $y_arr = array(-1 => '-Lọc theo Năm-');
            for ($i = 2008; $i <= date('Y'); $i++) {
                $y_arr[$i] = "---Năm $i-";
            }
            $m_arr = array(-1 => '-Lọc theo Tháng-');
            for ($i = 1; $i <= 12; $i++) {
                $m_arr[$i] = "---Tháng $i-";
            }
            $d_arr = array(0 => '-Lọc theo Ngày-');
            for ($i = 1; $i <= 31; $i++) {
                $d_arr[$i] = "---Ngày $i-";
            }

            $display->add('option_year', AZLib::getOption($y_arr, $year));
            $display->add('option_month', AZLib::getOption($m_arr, $mon));
            $display->add('option_day', AZLib::getOption($d_arr, $day));
            if ($created_time_from && $created_time_to) {
                $search_value .= ' AND (`time`  BETWEEN ' . $created_time_from . ' AND ' . $created_time_to . ')';
            } else {
                if ($created_time_from) {
                    $search_value .= ' AND `time` >= ' . $created_time_from;
                }
                if ($created_time_to) {
                    $search_value .= ' AND `time` <= ' . $created_time_to;
                }
            }
            if ($created_time_from) {
                $search_value .= ' AND `time` >= ' . $created_time_from;
            }
            if ($created_time_to) {
                $search_value .= ' AND `time` <= ' . $created_time_to;
            }

            $keywords = AZLib::trimSpace(AZLib::getParam('keywords'));
            $display->add('keywords', $keywords);

            if ($keywords) {
                $search_value .= ' AND des LIKE "%' . $keywords . '%" ';
            }

            $item_per_page = 20;

            $sql_count = 'SELECT count(*) AS total_img FROM item_image WHERE ' . $search_value;
            $total = DB::fetch($sql_count, 'total_img', 0);

            $paging = '';
            $items = array();

            $gallery_url = WEB_DIR . 'ajax.php' . Url::build_all(array('page_no'));

            if ($total) {
                $limit = '';
                $paging = AjaxGalleryPaging($limit, $total, $item_per_page, 5, $gallery_url, 'gallery_content');
                $sql = 'SELECT id, des, item_id, title, img_server, img_url, time FROM `item_image` WHERE ' . $search_value . ' ORDER BY id DESC ' . $limit;

                $re = DB::query($sql);

                if ($re) {
                    while ($row = mysql_fetch_assoc($re)) {
                        $row['image_url'] = $row['img_url'];
                        $row['img_url'] = AZLib::getImageThumb($row['img_url'], 100, 100, 0, $row['img_server']);
                        $items[$row['id']] = $row;
                    }
                }
            }

            $display->add('items', $items);
            $display->add('total', $total);
            $display->add('paging', $paging);
            $display->output('gallery_ajax', false, 'Personal');
            System::halt();
        } else {
            echo "Bạn chưa đăng nhập hoặc đã thoát khỏi hệ thống - Hãy đăng nhập lại!";
        }
    }

    function get_gallery_entry() {
        if (User::is_login()) {
            global $display;
            if ((User::have_permit(ADMIN_ITEM) || User::is_mod()) && (int) Url::get('user_id', 0) && (int) Url::get('user_id', 0) != User::id()) {
                $user_id = (int) Url::get('user_id', 0);
                $display->add('user_id', $user_id);
            }
            else
                $user_id=User::id();

            $search_value = ' user_id=' . $user_id . ' AND root_id=0 ';

            //search theo ngay thang nam
            //$year=(int)Url::get('year',date('Y'));
            $year = (int) Url::get('year', -1);
            //$mon= (int)Url::get('month',(int)date('m'));
            $mon = (int) Url::get('month', -1);
            $day = (int) Url::get('day', -1);

            if ($year == 0

                )$year = -1;
            if ($mon == 0

                )$mon = -1;
            if ($day == 0

                )$day = -1;

            $created_time_from = 0;
            $created_time_to = 0;

            if ($year != -1) {
                if ($mon != -1) {
                    if ($day != -1) {
                        $created_time_from = mktime(0, 0, 0, $mon, $day, $year);
                        $created_time_to = mktime(23, 59, 59, $mon, $day, $year);
                    } else {
                        $max_day = 31;
                        if (in_array($mon, array(4, 6, 9, 11))
                        
                            )$max_day = 30;
                        elseif ($mon == 2)
                            ($year % 4) ? $max_day = 28 : $max_day = 29;

                        $created_time_from = mktime(0, 0, 0, $mon, 1, $year);
                        $created_time_to = mktime(23, 59, 59, $mon, $max_day, $year);
                    }
                }
                else {
                    $created_time_from = mktime(0, 0, 0, 1, 1, $year);
                    $created_time_to = mktime(23, 59, 59, 12, 31, $year);
                }
            }

            $y_arr = array(-1 => '-Lọc theo Năm-');
            for ($i = 2008; $i <= date('Y'); $i++) {
                $y_arr[$i] = "---Năm $i-";
            }
            $m_arr = array(-1 => '-Lọc theo Tháng-');
            for ($i = 1; $i <= 12; $i++) {
                $m_arr[$i] = "---Tháng $i-";
            }
            $d_arr = array(0 => '-Lọc theo Ngày-');
            for ($i = 1; $i <= 31; $i++) {
                $d_arr[$i] = "---Ngày $i-";
            }

            $display->add('option_year', AZLib::getOption($y_arr, $year));
            $display->add('option_month', AZLib::getOption($m_arr, $mon));
            $display->add('option_day', AZLib::getOption($d_arr, $day));

            if ($created_time_from) {
                $search_value .= ' AND time >= ' . $created_time_from;
            }
            if ($created_time_to) {
                $search_value .= ' AND time <= ' . $created_time_to;
            }

            $keywords = AZLib::trimSpace(AZLib::getParam('keywords'));
            $display->add('keywords', $keywords);

            if ($keywords) {
                $search_value .= ' AND des LIKE "%' . $keywords . '%" ';
            }

            $item_per_page = 20;

            $sql_count = 'SELECT count(*) AS total_img FROM item_image WHERE ' . $search_value;
            $total = DB::fetch($sql_count, 'total_img', 0);

            $paging = '';
            $items = array();

            $gallery_url = WEB_DIR . 'ajax.php' . Url::build_all(array('page_no'));

            if ($total) {
                $limit = '';
                $paging = AjaxGalleryPaging($limit, $total, $item_per_page, 5, $gallery_url, 'gallery_content');
                $sql = 'SELECT id, des, item_id, title, img_server, img_url, time FROM `item_image` WHERE ' . $search_value . ' ORDER BY id DESC ' . $limit;
                $re = DB::query($sql);

                if ($re) {
                    while ($row = mysql_fetch_assoc($re)) {
                        $row['image_url'] = $row['img_url'];
                        $row['img_url'] = AZLib::getImageThumb($row['img_url'], 100, 100, 0, $row['img_server']);
                        $items[$row['id']] = $row;
                    }
                }
            }

            $display->add('items', $items);
            $display->add('total', $total);
            $display->add('paging', $paging);
            $display->output('gallery_ajax_entry', false, 'Personal');
            System::halt();
        } else {
            echo "Bạn chưa đăng nhập hoặc đã thoát khỏi hệ thống - Hãy đăng nhập lại!";
        }
    }

    function gallery_delete() {//Xoá ảnh
        global $display;
        $id = (int) Url::get('id');
        $return = 'fail';

        if ($id) {
            $image = DB::select('item_image', 'id=' . $id . (User::have_permit(ADMIN_IMAGE) ? '' : ' AND user_id=' . User::id()));
            if ($image) {
                if ($image['img_url']) {
                    //echo AZLib::ftp_image_delete_file($image['img_url'], $image['img_server']);
                    //exit;
                    AZLib::ftp_image_delete_file($image['img_url'], $image['img_server']); //Xoá ảnh gốc
                    //DB::query("UPDATE item SET img_url='' WHERE img_url='{$image['img_url']}' AND status IN(1,2) " . (User::have_permit(ADMIN_IMAGE) ? '' : ' AND user_id=' . User::id()));
                }

                //get Item_id
                $sql = "SELECT item_id FROM item_image WHERE (id = $id OR root_id = $id) " . (User::have_permit(ADMIN_IMAGE) ? '' : " AND user_id=" . User::id());
                $re = DB::query($sql);

                if ($re) {
                    $item = mysql_fetch_assoc($re);
                    if ($item["item_id"]) {
                        require_once ROOT_PATH . 'core/Item.php';
                        Item::get_item_images($item["item_id"], 1);
                    }
                }

                DB::delete('item_image', '(id=' . $id . ' OR root_id=' . $id . ')' . (User::have_permit(ADMIN_IMAGE) ? '' : ' AND user_id=' . User::id()));
                $return = 'success';
            }
        }
        echo $return;
        exit;
    }

    function gallery_bulk_delete() {//Xoá nhiều ảnh
        $arrIDs = explode(',', Url::get('ids'));
        $return = 'fail';

        if (count($arrIDs)) {
            foreach ($arrIDs as $imgID) {
                $image = DB::select('item_image', 'id=' . $imgID . (User::have_permit(ADMIN_IMAGE) ? '' : ' AND user_id=' . User::id()));
                if ($image) {
                    if ($image['img_url']) {
                        AZLib::ftp_image_delete_file($image['img_url'], $image['img_server']); //Xoá ảnh gốc
                        //DB::query("UPDATE item SET img_url='' WHERE img_url='{$image['img_url']}' AND status IN(1,2) " . (User::have_permit(ADMIN_IMAGE) ? '' : ' AND user_id=' . User::id()));
                    }

                    //get Item_id
                    $sql = "SELECT item_id FROM item_image WHERE (id = $imgID OR root_id = $imgID) " . (User::have_permit(ADMIN_IMAGE) ? '' : " AND user_id=" . User::id());
                    $re = DB::query($sql);

                    if ($re) {
                        $item = mysql_fetch_assoc($re);
                        if ($item["item_id"]) {
                            require_once ROOT_PATH . 'core/Item.php';
                            Item::get_item_images($item["item_id"], 1);
                        }
                    }

                    DB::delete('item_image', '(id=' . $imgID . ' OR root_id=' . $imgID . ')' . (User::have_permit(ADMIN_IMAGE) ? '' : ' AND user_id=' . User::id()));
                    $return = 'success';
                }
            }
        }
        echo $return;
        exit;
    }

}

//class

function AjaxGalleryPaging(&$limit='', $totalitem, $itemperpage, $numpageshow=10, $url_path='', $div_id='') {
    $st = '';
    $totalpage = ceil($totalitem / $itemperpage);
    if ($totalpage < 2) {
        //return 'Tổng số '.$totalitem.' ảnh';
        return '';
    }

    if (Url::get('page_no')) {
        $currentpage = Url::get('page_no');
    } else {
        $currentpage = 1;
    }

    $currentpage = round($currentpage);
    if ($currentpage <= 0 || $currentpage > $totalpage) {
        $currentpage = 1;
    }

    $limit = ' LIMIT ' . (($currentpage - 1) * $itemperpage) . ',' . $itemperpage;

    if ($currentpage > ($numpageshow / 2)) {
        $startpage = $currentpage - floor($numpageshow / 2);
        if ($totalpage - $startpage < $numpageshow) {
            $startpage = $totalpage - $numpageshow + 1;
        }
    } else {
        $startpage = 1;
    }
    if ($startpage < 1) {
        $startpage = 1;
    }

    if ($url_path != '')
        $url_path.='&' . 'page_no' . '=';
    else
        $url_path='?' . 'page_no' . '=';

    //Trang hien thoi
    //Link den trang truoc
    if ($currentpage > 1) {
        $st .= '<a href="javascript:void(0);" onclick = "ajax_gallery_paging(\'' . $url_path . ($currentpage - 1) . '\',\'' . $div_id . '\',\'' . $url_path . $currentpage . '\'); return false;" id="pgPrev">Trước</a>';
    }
    //Danh sach cac trang
    if ($startpage > 1) {
        $st .= '<a  href="javascript:void(0);" onclick = "ajax_gallery_paging(\'' . $url_path . '1\',\'' . $div_id . '\',\'' . $url_path . $currentpage . '\'); return false;">1</a> ';
        if ($startpage > 2) {
            $st .= '<strong>...</strong>'; //
        }
    }

    for ($i = $startpage; $i <= $startpage + $numpageshow - 1 && $i <= $totalpage; $i++) {
        if ($i != $startpage) {
            $st .= ''; //
        }
        if ($i == $currentpage) {
            if ($i > 1) {
                $st .='';
            }
            $st .= '<a href="javascript:void(0);" class="pgCurrent" id="pgCurrent">' . $i . '</a>';
        } else {
            if ($i > 1) {
                $st .='';
            }
            $st .= '<a  href="javascript:void(0);" onclick = "ajax_gallery_paging(\'' . $url_path . $i . '\',\'' . $div_id . '\',\'' . $url_path . $currentpage . '\'); return false;">' . $i . '</a> ';
        }
    }
    if ($i == $totalpage) {
        $st .= '<a  href="javascript:void(0);" onclick = "ajax_gallery_paging(\'' . $url_path . $totalpage . '\',\'' . $div_id . '\',\'' . $url_path . $currentpage . '\'); return false;">' . $totalpage . '</a> ';
    } elseif ($i < $totalpage) {
        $st .= '<strong>...</strong><a  href="javascript:void(0);" onclick = "ajax_gallery_paging(\'' . $url_path . $totalpage . '\',\'' . $div_id . '\',\'' . $url_path . $currentpage . '\'); return false;">' . $totalpage . '</a> ';
    }
    $st .= '';
    //Trang sau
    if ($currentpage < $totalpage) {
        $st .= '<a  href="javascript:void(0);" onclick = "ajax_gallery_paging(\'' . $url_path . ($currentpage + 1) . '\',\'' . $div_id . '\',\'' . $url_path . $currentpage . '\'); return false;" class="pgNext" >Sau</a>';
        //			$st1 .= '<div class="btn_pg_next floatLeft marginLeft5" onmouseout="this.className=\'btn_pg_next floatLeft marginLeft5\'" onmouseover="this.className=\'btn_pg_next_hover floatLeft marginLeft5\'" onclick="ajax_gallery_paging(\''.$url_path.($currentpage+1).'\',\''.$div_id.'\'); return false;"></div>';
    }
    return $st;
}

function disguise_curl($url) {
    $curl = curl_init();

    // Setup headers - I used the same headers from Firefox version 2.0.0.6
    // below was split up because php.net said the line was too long. :/
    $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
    $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
    $header[] = "Cache-Control: max-age=0";
    $header[] = "Connection: keep-alive";
    $header[] = "Keep-Alive: 300";
    $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
    $header[] = "Accept-Language: en-us,en;q=0.5";
    $header[] = "Pragma: "; // browsers keep this blank.

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
    curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
    curl_setopt($curl, CURLOPT_AUTOREFERER, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);

    $html = curl_exec($curl); // execute the curl command
    curl_close($curl); // close the connection

    return $html; // and finally, return $html
}

?>